/** 

*/

import java.sql.*;
import java.io.*;
import java.awt.event.*;

public class DBUtil {


   public static Connection connect(String url, String user, String passwd ) {
	try {
 	     DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	     Connection cnn = DriverManager.getConnection(url, user, passwd );
	     return cnn;
	 } catch (SQLException e ) {
	     e.printStackTrace(); return null;
	 }
   }

   public static ResultSet getResultSet(Statement stmt, String sqlSelect ) {

	ResultSet res = null; 
	try {
	     res = stmt.executeQuery( sqlSelect );
	     return res;
	} catch ( SQLException e) { e.printStackTrace(); return null; }
   }

   public static String getColumnNames( ResultSetMetaData meta, String colSeparator ) {

        StringBuffer  buf = new StringBuffer(400);	
	try {
	     int     colCount = meta.getColumnCount() ;
	     buf.append( meta.getColumnName(1) );
	     for ( int i = 2; i <= colCount; i++ )
		     buf.append (' ').append( colSeparator).append(' ').append(meta.getColumnName(i));
	     return new String( buf ) ;
	} catch ( SQLException e) { e.printStackTrace(); return null; }
   }

   // Write rows of record set into a file. Columns are separated by column separators.
   public static int resultSetToFile (ResultSet res , FileWriter fwtr, String colSeparator, int colCount ) {
        return resultSetToFile(res, fwtr, "", colSeparator, "\n", colCount);
   }
  
   // Output rows of result set into a file. The format of a row beginning with rowBegin string and ending with
   // rowEnd string. the columns are separated by column separator. To output records as a HTML table rows,
   // call the function with following parameters:   
   // 				resultSetToFile( res, wftr, "<TR><TD>", "</TD><TD>", </TD></TR>\n"
   public static int resultSetToFile (ResultSet res , FileWriter fwtr,
		   String rowBegin, String colSeparator, String rowEnd, int colCount ) {
       int recordCount = 0;
       try {
	   while ( res.next() ) {
	      fwtr.write( rowBegin + res.getString(1) );
	      for ( int i = 2; i <= colCount; i ++ ) fwtr.write( colSeparator + " " + res.getString(i) );  
	      fwtr.write( rowEnd );
	      recordCount++; 
	   }
	   return recordCount;
       } catch ( SQLException e) { e.printStackTrace(); return recordCount; }
         catch ( IOException e2) { e2.printStackTrace(); return recordCount; }
   }

}
